package com.epam.ws.anatomist.example;

import java.util.Enumeration;
import java.util.Properties;
import java.util.UUID;

import org.w3c.dom.Document;

import com.epam.ws.anatomist.common.ApplicationStorage;
import com.epam.ws.anatomist.example.bindings.Request;
import com.epam.ws.anatomist.message.MessageBuilder;
import com.epam.ws.anatomist.message.MessageConverter;
import com.epam.ws.anatomist.message.TemplateEntity;
import com.epam.ws.anatomist.message.TemplatePojoEntity;

public class RequestFactory
{

	private ApplicationStorage applicationStorage;

	public RequestFactory(String configPath)
	{
		this.applicationStorage = ApplicationStorage.newInstance(configPath);
	}

	public Request createRequest()
	{
		Request request = new Request();
		request.setId(12);
		request.setName("A");
		return request;
	}

	public Operation createRequestHolder(String requestName, Properties customProperties)
	{
		TemplatePojoEntity templatePojoEntity = applicationStorage.getTemplatePojoEntity(requestName);
		TemplateEntity templateEntity = templatePojoEntity.getTemplateEntity();
		Properties dataSource = templateEntity.getDataSource();
		if (dataSource == null)
		{
			dataSource = customProperties;
		}
		else
		{
			dataSource.putAll(customProperties);
		}
		processProperties(dataSource);
		Operation messageHolder = new Operation();
		messageHolder.setRequest((IMessage) MessageBuilder.buildPojoEntity(templatePojoEntity));
		messageHolder.setProperties(dataSource);
		return messageHolder;
	}

	public Operation getOperation(String operationName)
	{
		return new Operation();
	}

	public Document createControlDocument(String controlXmlCfgName, Properties customData)
	{
		String controlXml = createControlXml(controlXmlCfgName, customData);
		return MessageConverter.convertXmlToDocument(controlXml);
	}

	public String createControlXml(String controlXmlCfgName, Properties customData)
	{
		TemplateEntity templateEntity = applicationStorage.getTemplateEntity(controlXmlCfgName);
		Properties dataSource = templateEntity.getDataSource();
		if (dataSource == null)
		{
			templateEntity.setDataSource(customData);
		}
		else
		{
			dataSource.putAll(customData);
		}
		return MessageBuilder.buildXmlMessage(templateEntity);
	}

	private synchronized void processProperties(Properties properties)
	{
		if (properties == null)
		{
			return;
		}
		Enumeration<Object> keys = properties.keys();
		while (keys.hasMoreElements())
		{
			String key = (String) keys.nextElement();
			String propertyValue = properties.getProperty(key);
			if ("generateGUID()".equals(propertyValue.trim()))
			{
				String guid = UUID.randomUUID().toString();
				properties.put(key, guid);
			}
		}
	}

}
